﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Linq;

namespace NetMongo.Helper
{

    public static class JsonHelper
    {
        private static JsonSerializerSettings _jsonSettings;

        static JsonHelper()
        {
            IsoDateTimeConverter datetimeConverter = new IsoDateTimeConverter();
            datetimeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            JavaScriptDateTimeConverter dateConverter = new JavaScriptDateTimeConverter();

            _jsonSettings = new JsonSerializerSettings();
            _jsonSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
            _jsonSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            _jsonSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            _jsonSettings.Converters.Add(new JavaScriptDateTimeConverter());
        }



        /// <summary>
        /// 将指定的对象序列化成 JSON 数据。
        /// </summary>
        /// <param name="obj">要序列化的对象。</param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            try
            {
                if (null == obj)
                    return null;
                if (string.IsNullOrWhiteSpace(obj.ToString().Trim()))
                    return string.Empty;

                return JsonConvert.SerializeObject(obj, Formatting.None, _jsonSettings);
            }
            catch (Exception ex)
            {
                Logger.Log("NetMongo.Helper.JsonHelper.ToJson Exception：" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 将指定的 JSON 数据反序列化成指定对象。
        /// </summary>
        /// <typeparam name="T">对象类型。</typeparam>
        /// <param name="json">JSON 数据。</param>
        /// <returns></returns>
        public static T DeserializeObject<T>(this string json, JsonConverter converter = null)
        {
            try
            {
                if (converter == null) converter = new DateTimeConverter();
                return JsonConvert.DeserializeObject<T>(json, converter);
            }
            catch (Exception ex)
            {
                Logger.Log("NetMongo.Helper.JsonHelper.ToJson Exception：" + ex.Message+ex.TargetSite);
                return default(T);
            }
        }

    }

    public class JavaScriptDateTimeConverter:JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DateTime time = DateTime.MinValue;
            DateTime.TryParse(reader.Value.ToString(), out time);

            if (time > DateTime.MinValue)
            {
                return time;
            }
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 8, 0, 0));
            return (DateTime.Parse(reader.Value.ToString()) - startTime);            
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {            
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 8, 0, 0));
            writer.WriteValue((DateTime.Parse(value.ToString()) - startTime).TotalMilliseconds);
        }

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override bool CanConvert(Type objectType)
        {
            return _types.Any(t => t == objectType);
        }

        public Type[] _types;

        public JavaScriptDateTimeConverter(params Type[] types)
        {
            this._types = types;
        }
    }
}
